package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.AppAllows;
import com.letv.whatslive.model.CP;
import com.letv.whatslive.model.convert.AppAllowsConvert;
import com.letv.whatslive.model.convert.CPConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

//2015.11.4

/**
 * 渠道操作DAO
 * Created by shenyue on 2015/11/4.
 */
@Repository
public class CPDAO extends BaseDAO {
    protected String collectionName = "cp";

    private static final Logger logger = LoggerFactory.getLogger(CPDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public Long saveOrUpdate(CP cp) {
        DBObject query = new BasicDBObject("_id", cp.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(cp.getId()==null)
                cp.setId(getAutoIncrementId());
            dbo = CPConvert.castCPToDBObject(cp);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();

            if(StringUtils.isNotBlank(cp.getPcode())){
                update.put("pcode",cp.getPcode());
            }

            if(StringUtils.isNotBlank(cp.getCpDescribe())){
                update.put("cpDescribe",cp.getCpDescribe());
            }
            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
            return cp.getId();
        }

        return 0L;
    }

    /**
     * 根据查询条件查询所有的渠道列表
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<CP> getCPListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<CP> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                CP cp = CPConvert.castDBObjectToCP(dbObject);
                result.add(cp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("pcode") != null) {
                query.put("pcode", ObjectUtils.toString(params.get("pcode")));
            }
        }

        return query;
    }


    /**
     * 根据条件获取相应的渠道列表
     * @param params
     * @return
     */
    public List<CP> getAllCPByParams(Map<String, Object> params){
        List<CP> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                CP cp = CPConvert.castDBObjectToCP(dbObject);
                result.add(cp);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据设备Id获取渠道
     * @param id
     * @return
     */
    public CP getCPById(Long id) {
        BasicDBObject query = new BasicDBObject();
        CP cp = new CP();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            cp = CPConvert.castDBObjectToCP(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return cp;
    }

    public CP saveCP(CP cp) {
        try {
            cp.setId(getAutoIncrementId());
            DBObject dbo = CPConvert.castCPToDBObject(cp);
            WriteResult wr = this.dbCollection.insert(dbo);
            return cp;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
}